<template>
  <!-- 线路线路管理 -->
  <div class="line-m">
    <!--  条件搜索  -->
    <el-form :inline="true" :model="conditionForTransportLine" class="demo-form-inline">
      <el-form-item label="线路编号">
        <el-input v-model="conditionForTransportLine.lineNumber" placeholder="线路编号"></el-input>
      </el-form-item>

      <el-form-item label="线路名称">
        <el-input v-model="conditionForTransportLine.name" placeholder="线路名称"></el-input>
      </el-form-item>

      <el-form-item label="线路类型">
        <el-select v-model="conditionForTransportLine.transportLineTypeId" filterable placeholder="线路类型">
          <el-option label="所有类型" :value="''"></el-option>
          <el-option v-for="lineType in lineTypeList" :key="lineType.id" :label="lineType.name"
                     :value="lineType.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary"
                   @click="queryByConditionAndPage(TransportLinePageInfo.pageNum, TransportLinePageInfo.pageSize)">
          查 询
        </el-button>
        <el-button type="primary"
                   @click="conditionForTransportLine = {}; queryByConditionAndPage(TransportLinePageInfo.pageNum, TransportLinePageInfo.pageSize)">
          重 置
        </el-button>
      </el-form-item>
    </el-form>

    <el-divider></el-divider>

    <el-button type="primary" @click="showLine(null)">新增线路</el-button>
    <!--  数据展示  -->
    <el-table :data="TransportLinePageInfo.list" @expand-change="matchTransportTrips" :expand-row-keys="expands"
              :row-key="getRowKey" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <el-table :data="transportTripsList" stripe style="width: 100%">
            <el-table-column prop="tripsName" label="车次名称"></el-table-column>
            <el-table-column prop="departureTime" label="发车时间"></el-table-column>
            <el-table-column label="车辆司机安排">
              <template slot-scope="prop">
                {{ prop.row.truckLicensePlate }} -- {{ prop.row.driverName }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="prop">
                <el-button type="text" @click="operateForTrips.lineName = row.name; showTrips(prop.row)">编辑车次
                </el-button>
                <el-button style="color: red" type="text" @click="deleteTrips(row, prop.row)">删除车次</el-button>
                <el-button type="text" @click="showTruck(prop.row, row)">安排车辆</el-button>
                <el-button type="text" @click="showDriver(prop.row, row)">安排司机</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="线路编号" prop="lineNumber"></el-table-column>
      <el-table-column label="线路名称" prop="name"></el-table-column>
      <el-table-column label="线路类型">
        <template slot-scope="{ row }">
          <i v-for="lineType in lineTypeList" v-show="row.transportLineTypeId == lineType.id">{{ lineType.name }}</i>
        </template>
      </el-table-column>
      <el-table-column label="起始地机构">
        <template slot-scope="{ row }">
          <i v-for="coreOrg in coreOrgList" v-show="row.startAgencyId == coreOrg.id">{{ coreOrg.name }}</i>
        </template>
      </el-table-column>
      <el-table-column label="目的地机构" prop="endAgencyId">
        <template slot-scope="{ row }">
          <i v-for="coreOrg in coreOrgList" v-show="row.endAgencyId == coreOrg.id">{{ coreOrg.name }}</i>
        </template>
      </el-table-column>
      <el-table-column label="距离(千米)" prop="distance"></el-table-column>
      <el-table-column label="平均成本(元)" prop="cost"></el-table-column>
      <el-table-column label="预计时间(分钟)" prop="estimatedTime"></el-table-column>
      <el-table-column label="线路地图">
        <template slot-scope="{ row }">
          <el-button type="text" icon="el-icon-location-outline" @click="initAMap(row)">地图</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{row}">
          <el-button type="text" @click="showLine(row)">修 改</el-button>
          <el-button style="color: red" type="text" @click="deleteById(row.id)">删 除</el-button>
          <el-button type="text"
                     @click="operateForTrips = {}; operateForTrips.transportLineId = row.id; operateForTrips.lineName = row.name; showTrips(null)">
            增加车次
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 地图展示对话框 -->
    <el-dialog
      title="路线详情"
      :visible.sync="mapShow"
      width="50%"
      center>
      <MyContainer ref="myContainer" :end-agency="endAgency" :start-agency="startAgency"></MyContainer>
    </el-dialog>

    <!--  分页  -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="TransportLinePageInfo.pageNum"
      :page-sizes="[5, 10, 15, 20, 25]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="TransportLinePageInfo.total">
    </el-pagination>

    <!-- 线路对话框展示 -->
    <el-dialog :title="dialogTitle" :visible.sync="centerDialogVisible" width="40%"
               center>
      <el-form label-position="right" label-width="110px" :model="operateForTransportLine">
        <el-form-item label="线路编号">
          <el-input v-model="operateForTransportLine.lineNumber" placeholder="线路编号"></el-input>
        </el-form-item>

        <el-form-item label="线路名称">
          <el-input v-model="operateForTransportLine.name" placeholder="线路名称"></el-input>
        </el-form-item>

        <el-form-item label="线路类型">
          <el-select v-model="operateForTransportLine.transportLineTypeId" placeholder="线路类型">
            <el-option v-for="lineType in lineTypeList" :label="lineType.name" :key="lineType.id"
                       :value="lineType.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="起始机构线路">
          <el-select v-model="operateForTransportLine.startAgencyId" placeholder="起始机构线路">
            <el-option v-for="coreOrg in coreOrgList" :key="coreOrg.id" :label="coreOrg.name"
                       :value="coreOrg.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="终点机构线路">
          <el-select v-model="operateForTransportLine.endAgencyId" placeholder="终点机构线路">
            <el-option v-for="coreOrg in coreOrgList" :key="coreOrg.id" :label="coreOrg.name"
                       :value="coreOrg.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="距离(千米)">
          <el-input v-model="operateForTransportLine.distance" placeholder="距离(千米)"></el-input>
        </el-form-item>

        <el-form-item label="成本(元)">
          <el-input v-model="operateForTransportLine.cost" placeholder="成本(元)"></el-input>
        </el-form-item>

        <el-form-item label="预计时间(分钟)">
          <el-input v-model="operateForTransportLine.estimatedTime" placeholder="预计时间(分钟)"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="commitOperate">提 交</el-button>
          <el-button type="primary" @click="centerDialogVisible = false; operateForTransportLine = {}">关 闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 车次对话框展示 -->
    <el-dialog :title="dialogTitle" :visible.sync="tripsVisible" width="40%"
               center>
      <el-form label-position="right" label-width="110px" :model="operateForTrips">
        <el-form-item label="线路名称">
          <el-input disabled v-model="operateForTrips.lineName" placeholder="线路名称"></el-input>
        </el-form-item>

        <el-form-item label="车次名称">
          <el-input v-model="operateForTrips.name" placeholder="车次名称"></el-input>
        </el-form-item>

        <el-form-item label="发车时间">
          <el-time-picker placeholder="选择时间" v-model="operateForTrips.departureTime"></el-time-picker>
          <el-divider direction="vertical"></el-divider>
          <el-select v-model="operateForTrips.period" placeholder="请选择">
            <el-option label="天" :value="1" selected></el-option>
            <el-option label="周" :value="2"></el-option>
            <el-option label="月" :value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="operateTrips">提 交</el-button>
          <el-button type="primary" @click="tripsVisible = false; operateForTrips = {}">关 闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 车辆对话框展示 -->
    <el-dialog title="安排车辆" :visible.sync="truckVisible" width="40%"
               center>
      <el-form label-position="right" label-width="110px" :model="operateForTruck">
        <el-form-item label="线路名称">
          <el-input readonly v-model="operateForTruck.lineName" placeholder="线路名称"></el-input>
        </el-form-item>

        <el-form-item label="车次名称">
          <el-input readonly v-model="operateForTruck.tripsName" placeholder="车次名称"></el-input>
        </el-form-item>

        <el-form-item label="发车时间">
          <el-input readonly v-model="operateForTruck.departureTime" placeholder="发车时间"></el-input>
        </el-form-item>

        <el-form-item label="安排车辆">
          <el-cascader
            :options="truckList"
            :props="{label: 'licensePlate', value: 'id', children: 'pdTruck'}"
            v-model="operateForTruck.truckId"
            :show-all-levels="false"></el-cascader>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="commitTruck">提 交</el-button>
          <el-button type="primary" @click="truckVisible = false; operateForTruck = {}">关 闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 司机对话框展示 -->
    <el-dialog :title="dialogTitle" :visible.sync="driverVisible" width="40%"
               center>
      <el-form label-position="right" label-width="110px" :model="operateForDriver">
        <el-form-item label="线路名称">
          <el-input readonly v-model="operateForDriver.lineName" placeholder="线路名称"></el-input>
        </el-form-item>

        <el-form-item label="车次名称">
          <el-input readonly v-model="operateForDriver.tripsName" placeholder="车次名称"></el-input>
        </el-form-item>

        <el-form-item label="发车时间">
          <el-input readonly v-model="operateForDriver.departureTime" placeholder="发车时间"></el-input>
        </el-form-item>

        <el-form-item label="车辆司机安排">
          <el-tag>车牌：{{ operateForDriver.tripsName }}</el-tag>
          ---
          <el-select v-model="operateForDriver.userId" filterable placeholder="请选择">
            <el-option v-for="driver in driverList" :key="driver.id" :label="driver.name"
                       :value="driver.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="commitDriver">提 交</el-button>
          <el-button type="primary" @click="driverVisible = false; operateForDriver = {}">关 闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import MyContainer from "@/views/amap/MyContainer.vue";
import row from "element-ui/packages/row";

export default {
  computed: {
    row() {
      return row
    }
  },
  components: {
    MyContainer,
  },
  data() {
    return {
      allData: [],
      expands: [],
      serverUnitTable: [],

      map: null,
      // 查询条件
      conditionForTransportLine: {},
      // 返回的pageInfo
      TransportLinePageInfo: {},
      // 控制对话框是否展示
      centerDialogVisible: false,
      // 对话框的title
      dialogTitle: '',
      // 新增和修改的操作条件
      operateForTransportLine: {},
      // 判断是添加还是修改的tag
      operateTag: false,
      // 线路类型集合
      lineTypeList: [],
      // 地图展示flag
      mapShow: false,
      // startAgency 起始机构
      startAgency: '',
      // endAgency 目的地机构
      endAgency: '',
      // 车次集合
      transportTripsList: [],
      // 组织机构集合
      coreOrgList: [],
      // areaList
      areaList: [],
      // 操作车次
      operateForTrips: {},
      tripsVisible: false,

      truckList: [],
      driverList: [],

      truckVisible: false,
      driverVisible: false,

      operateForTruck: {},
      operateForDriver: {},
    }
  },
  created() {
    // 调用组织机构查询
    this.queryAllCoreOrg();
    // 初始化线路类型集合
    this.queryAllLineType();
    this.queryArea();
    this.queryTrucksAndDrivers();
  },
  beforeMount() {
    // 调用条件分页查询线路
    this.queryByConditionAndPage(1, 5);
  },
  methods: {
    // 点击安排车辆
    showTruck(tripsRow, lineRow) {
      console.log(tripsRow, lineRow)
      this.operateForTruck.lineName = lineRow.name;
      this.operateForTruck.tripsName = tripsRow.tripsName;
      this.operateForTruck.departureTime = tripsRow.departureTime;
      this.operateForTruck.transportTripsId = tripsRow.tripsId;

      this.truckVisible = true;
    },

    commitTruck() {
      this.operateForTruck.truckId = this.operateForTruck.truckId[1];

      // bindTripsAndTruck
      axios.post('/api/pd-base/pd-transport-trips-truck-driver/bindTripsAndTruck', this.operateForTruck).then(res => {
        if (res.data.data === 200) {
          this.$message.success('绑定成功')
        }
        this.truckVisible = false;
      })
    },

    // 点击安排司机， 需要先有安排车辆才能安排司机
    showDriver(tripsRow, lineRow) {
      if (tripsRow.truckId === undefined) {
        this.$message.warning('还没有安排车辆');
      } else {
        // 根据车辆id truckId和车次id tripsId 绑定司机id
        this.operateForDriver.lineName = lineRow.name;
        this.operateForDriver.tripsName = tripsRow.tripsName;
        this.operateForDriver.departureTime = tripsRow.departureTime;
        this.operateForDriver.transportTripsId = tripsRow.tripsId;
        this.operateForDriver.truckId = tripsRow.truckId;
        this.operateForDriver.userId = tripsRow.accountId;
        this.driverVisible = true;
      }
    },

    commitDriver() {
      console.log(this.operateForDriver)
      // bindTripsAndDriver
      axios.post('/api/pd-base/pd-transport-trips-truck-driver/bindTripsAndDriver', this.operateForDriver).then(res => {
        if (res.data.data === 200) {
          this.$message.success('绑定成功');
        }
        this.driverVisible = false;
      })
    },

    // 查询车辆，司机
    queryTrucksAndDrivers: async function () {
      // 查询车辆
      let res = await axios.get('/api/pd-base/pd-truck/queryAllByFleetGroup');
      this.truckList = res.data.data;
      // 查询司机
      let res2 = await axios.get('/api/pd-aggregation/pd-auth-user/queryAllDriver');
      this.driverList = res2.data.data;
    },


    // 点击添加或修改车次展示
    showTrips(row) {
      if (row == null) {
        // 添加
        this.dialogTitle = '添加'
        this.operateTag = true;
      } else {
        // 修改
        this.operateForTrips.name = row.tripsName;
        this.operateForTrips.departureTime = row.departureTime;
        this.operateForTrips.transportLineId = row.transportLineId;
        this.dialogTitle = '修改'
        this.operateTag = false;
      }
      this.tripsVisible = true;
    },

    // 添加或修改车次
    operateTrips: async function () {
      let url;
      if (this.operateTag) {
        url = `addTransportTrips`;
      } else {
        url = `updateTransportTrips`;
      }
      let res = await axios.post(`/api/pd-base/pd-transport-trips/${url}`, this.operateForTrips);

      res.data.code === 200 ? this.$message.success('操作成功！！！') : this.$message.success('操作失败！！！');

      await this.queryByConditionAndPage(this.TransportLinePageInfo.pageNum, this.TransportLinePageInfo.pageSize);
      this.tripsVisible = false
    },

    // 删除车次
    deleteTrips: async function (lineRow, tripsRow) {
      // 根据车次id，线路id删除车次表的数据
      console.log(lineRow, tripsRow)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await axios.get(`/api/pd-base/pd-transport-trips/deleteTripsByTripsIdAndLineId/${lineRow.id}/${tripsRow.tripsId}`)
        // await this.matchTransportTrips()

        let res = await axios.get(`/api/pd-aggregation/pd-truck/queryTripsDriverTruckByTransportLineId/${lineRow.id}`);
        this.transportTripsList = res.data.data;
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },

    getRowKey(row) {
      return row.id;
    },

    // 展开表格触发事件
    matchTransportTrips: async function (row, expandedRows) {
      if (expandedRows.length > 0) { // 展开时执行
        this.expands = []
        this.expands.push(row.id)
        this.tankInfoTable = []
        for (let m = 0; m < this.allData.length; m++) {
          if (this.allData[m].f001 == row.sydw) {
            this.tankInfoTable.push(this.allData[m])
          }
        }
      }
      this.transportTripsList = []
      // 查询车次，根据车次查询出对应车辆，以及车辆对应的司机
      let res = await axios.get(`/api/pd-aggregation/pd-truck/queryTripsDriverTruckByTransportLineId/${row.id}`);

      console.log('车辆，以及车辆对应的司机', res.data.data);

      this.transportTripsList = res.data.data;
    },

    // 查询所有area
    queryArea: async function () {
      // /api/pd-aggregationcjj/pd-area/queryArea
      let res = await axios.get('/api/pd-aggregationcjj/pd-area/queryArea');
      this.areaList = res.data.data;
    },

    //展示地图
    initAMap: async function (row) {
      // row 里面有起始机构id，目的地机构id，根据两个id分别查询出起始机构数据对象和目的地机构对象
      let resStart = await axios.get(`/api/pd-aggregation/pd-core-org/queryById/${row.startAgencyId}`);
      // 过滤出起始机构对应的省市区和address拼接成一个完整地址
      let orgStartAgency = resStart.data.data;
      if (orgStartAgency == null) {
        this.$message.error('地址不对')
      }
      // 省
      let startProvince = this.areaList.filter(item => item.id == orgStartAgency.provinceId);
      // 市
      let startCity = startProvince[0].pdAreaVOS.filter(item => item.id == orgStartAgency.cityId);
      // 区
      let startCounty = startCity[0].pdAreaVOS.filter(item => item.id == orgStartAgency.countyId);
      // 跟详细address拼接, 起始点地址
      this.startAgency = startProvince[0].name + startCity[0].name + startCounty[0].name;


      let resEnd = await axios.get(`/api/pd-aggregation/pd-core-org/queryById/${row.endAgencyId}`);
      // 过滤出起始机构对应的省市区和address拼接成一个完整地址
      let orgEndAgency = resEnd.data.data;
      if (orgEndAgency == null) {
        this.$message.error('地址不对')
      }
      // 省
      let endProvince = this.areaList.filter(item => item.id == orgEndAgency.provinceId);
      // 市
      let endCity = endProvince[0].pdAreaVOS.filter(item => item.id == orgEndAgency.cityId);
      // 区
      let endCounty = endCity[0].pdAreaVOS.filter(item => item.id == orgEndAgency.countyId);
      // 跟详细address拼接, 终点地址
      this.endAgency = endProvince[0].name + endCity[0].name + endCounty[0].name;

      this.mapShow = true;
      this.$refs.myContainer.initMap();
    },

    // 查询所有组织机构
    queryAllCoreOrg: async function () {
      let res = await axios.get('/api/pd-aggregation/pd-core-org/queryAll');
      if (res.data.code === 200) {
        this.coreOrgList = res.data.data;
      }
    },

    // 查询所有线路类型
    queryAllLineType: async function () {
      let res = await axios.get('/api/pd-base/pd-transport-line-type/queryAll');
      if (res.data.code === 200) {
        this.lineTypeList = res.data.data;
      }
    },

    // 条件分页查询 线路
    queryByConditionAndPage: async function (currentPage, pageSize) {
      let res = await axios.post(`/api/pd-base/pd-transport-line/queryByConditionAndPage/${currentPage}/${pageSize}`, this.conditionForTransportLine);
      if (res.data.code === 200) {
        // 查询成功
        this.TransportLinePageInfo = res.data.data;
      } else {
        // 查询失败
      }
    },

    // 点击添加或修改展示对话框
    showLine: async function (row) {
      this.centerDialogVisible = true;

      if (row === null) {
        // 添加
        this.dialogTitle = '添 加';
        this.operateForTransportLine = {}
        this.operateTag = true;
      } else {
        // 修改
        this.dialogTitle = '修 改';
        this.operateTag = false;
        this.operateForTransportLine = JSON.parse(JSON.stringify(row));
      }
    },

    // 提交 添加或修改
    commitOperate: async function () {
      let url;
      if (this.operateTag) {
        url = `insert`;
        this.operateForTransportLine.agencyId = this.operateForTransportLine.startAgencyId;
      } else {
        url = `updateById`;
      }
      let res = await axios.post(`/api/pd-base/pd-transport-line/${url}`, this.operateForTransportLine);

      res.data.code === 200 ? this.$message.success('操作成功！！！') : this.$message.success('操作失败！！！');

      await this.queryByConditionAndPage(this.TransportLinePageInfo.pageNum, this.TransportLinePageInfo.pageSize);
      this.centerDialogVisible = false
    },

    // 根据id删除线路
    deleteById: async function (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await axios.get(`/api/pd-base/pd-transport-line/deleteById/${id}`);
        if (res.data.code === 200) {
          this.$message.success('删除成功')
          await this.queryByConditionAndPage(this.TransportLinePageInfo.pageNum, this.TransportLinePageInfo.pageSize);
          this.centerDialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 每页显示条数改变
    handleSizeChange(val) {
      this.queryByConditionAndPage(this.TransportLinePageInfo.pageNum, val);
    },

    // 当前页码改变
    handleCurrentChange(val) {
      this.queryByConditionAndPage(val, this.TransportLinePageInfo.pageSize);
    }
  }
}
</script>

<style scoped>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.line-m {
  margin-top: 20px;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>
